(function (root, factory) {
        if (typeof define === 'function' && define.amd) {
            define(['underscore'], factory);
        } else {
            root.AjaxDataSource = factory();
        }
    }(this, function () {
    	
 
        var AjaxDataSource = function(options) {
                this._formatter = options.formatter;
                this._columns = options.columns;
                this._delay = options.delay || 0;
                this._data = options.data;
                this._count=0;
 
                // allows us to pass in the URL to get data from via Ajax
                this._url = options.url;
                this._queryData=options.queryData?options.queryData:{};
 
                // allows us to initially load data via Ajax,fasle means load from client
                this._server = options.server || false;
                //是否在server端进行排序，如果否，则由浏览器完成排序，否则将排序字段传给server由server来完成排序。
                //todo 在gridrender的时候判断当前页码是否发生改变，如果改变，则向服务器发送请求，否则不发送请求
                this._serverSorting=options.serverSorting||false;
                
                this._del=[];//记录删除的行
        		this._update=[];//记录要更新的行
        		this._seleted=[];//记录选中的行
        		//this._currentPageNO;//记录当前页号
        		
            };
 
       AjaxDataSource.prototype = {
            columns: function() {
                return this._columns;
            },
            //设置查询参数.方便更改查询条件
            setQueryData:function(data){
            	this._queryData=data;
            },
            getSelectedRowIndex:function(){
    			return this._seleted;
    		},
    		getSelectedRow:function(){//返回被选中的行的数据，如果选择中多行，取第一次选中的行的数据。
    			var index=parseInt(this._seleted[0],10);
    			if(!isNaN(index)){
    				return this._data[index];
    			}
    		},
    		getSelectedRows:function(){//返回被选中的行的数据。
    			var rows=[],_data=this._data;
    			$(this._seleted).each(function(data,m){
    				var index=parseInt(m,10);
    				rows.push(_data[index]);
    			});
    			return rows;
    		},
    		getDeleteRow:function(){
    			return this._del;
    		},
    		getData:function(){
    			return this._data;
    		},
    		delSelectedRow:function(){
    			var self=this,narray=[];
    			$(this._seleted).each(function(i,data){
    				var index=parseInt(data,10);
    				delete self._data[index];
    			});
    			
    			for(index in self._data){
    				narray.push(self._data[index]);
    			}
    			self._data=narray;
    			self._seleted=[];
    		},
    		
    		insertRows:function(rows){
    			
    			if(jQuery.type(rows) === "array"){
    				$.merge(this._data, rows);
    				$.merge(this._update,rows);
    			}
    			//do nothing when the param is not an array
    			
    		},
 
            data: function(options, callback) {
                self = this;
 
                setTimeout(function() {
                    var data = $.extend(true, [], self._data),
                        count = data.length,
                        pageStart=options.pageIndex*options.pageSize,
                        size=options.pageSize||5;
                        
                        // reload the DataGrid via ajax if any of these conditions are true
                        if (self._server)
                        {
                            if(options.reload||self._serverSorting || self.pageStart!=pageStart || self.pageSize!=size){
                            	$.ajax(self._url, {
                                    dataType: 'json',
                                    async: false,
                                    type: 'POST',
                                    data:$.extend(self._queryData,{"start":pageStart,"size":size,"sort":options.sortProperty,"sortDirection":options.sortDirection}),
                                    success:function(back){
                                    	data = back.data;
                                        count = back.total;
                                        self.pageStart=options.pageIndex*options.pageSize;
                                        self.pageSize=options.pageSize||5;
                                        self._data=data;
                                        self._count=count;
                                    }
                                });
                            }else{
                            	 data=self._data;
                            	 count=self._count;
                            }
                            // After data has been loaded via ajax, set these optional parameter back to their original state
                           // self.reload_data_from_server = false;
                        }
                     
 
                    // SEARCHING
                    if (options.search) {
                        
                    }
 
                    // SORTING
                    if (options.sortProperty) {
                    	data = _.sortBy(data, options.sortProperty);
                        if (options.sortDirection === 'desc') data.reverse();
                    }
 
                    // FILTERING
                    if (options.filter) {
                    	 
                    }
                    
                 // PAGING
                    startIndex = options.pageIndex * options.pageSize,
                    endIndex = startIndex + options.pageSize,
                    end = (endIndex > count) ? count : endIndex,
                    pages = Math.ceil(count / options.pageSize),
                    page = options.pageIndex + 1,
                    start = startIndex + 1;
 
                    self._del=[];//清空记录删除的行数组
            		self._update=[];//清空记录要更新的行数组
            		self._seleted=[];//清空记录选中的行数组
                   
                   // this._currentPageNO=page;//记录当前页号
                    
                    if (self._formatter)
                        self._formatter(data);
 
                    
                    callback({
                        data: data,
                        start: start,
                        end: end,
                        count: count,
                        pages: pages,
                        page: page
                    });
                    
                }, this._delay);
            }
        };
 
        return AjaxDataSource;
    }));
 